﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Microsoft.HomeServer.Common.Client;
using Microsoft.HomeServer.Controls;
using RouterControl.Whs.SingletonService;

namespace RouterControl.WhsAddIn.SettingsControls
{
    public partial class ErrorReporting : SettingsControlBase
    {
        public ErrorReporting(RouterControlSettingsTab2 tab)
			: base(tab)
		{
			if (_log.IsDebugEnabled)
				_log.Debug("Initialization start");

			try
			{
				InitializeComponent();

                this.lineBox.Header.Text = Properties.Resources.txtSettingsErrorReporting;
                this.statusLabel.Text = Properties.Resources.txtLoading;

                // register for settings save
                _tab.OnSettingsCommitted += new RouterControlSettingsTab2.OnSettingsCommittedDelegate(OnSettingsCommitted);

				// done
				if (_log.IsDebugEnabled)
					_log.Debug("Initialization done");
			}
			catch (Exception ex)
			{
				_log.Fatal("Failed to initialize", ex);

				throw;
			}
		}

        private void OnSettingsCommitted(RouterControlSettingsTab2.SettingsCache cache)
        {
            UpdateSubmittingAllowed();
        }

        private void ErrorReporting_Load(object sender, EventArgs e)
        {
			if (_log.IsDebugEnabled)
				_log.Debug("Loading start");

			try
			{
                this.allowSubmitting.Checked = _tab.Settings.EnableErrorReporting;

                UpdateSubmittingAllowed();

                // done
                if (_log.IsDebugEnabled)
                    _log.Debug("Loading done");
            }
            catch (Exception ex)
            {
                _log.Fatal("Loading failed", ex);

                throw;
            }
        }

        private void UpdateSubmittingAllowed()
        {
            if (_singletonService.Channel.IsErrorReportsSubmissionEnabled())
            {
                UpdateErrorReportingStatus();

                this.updateTimer.Enabled = true;
            }
            else
            {
                this.statusImage.Image = CommonImages.StatusCritical24;

                this.updateTimer.Enabled = false;

                // update status label
                var status = _singletonService.Channel.GetErrorReportingStatus();

                this.statusLabel.Text = string.Format(
                    Properties.Resources.txtErrorReportingStatusDisabled,
                    status.Unsubmitted,
                    status.Submitted,
                    status.Progress
                    );
            }
        }

        private void UpdateErrorReportingStatus()
        {
            try
            {
	            var status = _singletonService.Channel.GetErrorReportingStatus();
	
	            if (status.IsSubmitting)
	            {
	                this.statusImage.Image = Properties.Resources.imgProgressAnim;
	
	                this.statusLabel.Text = string.Format(
	                    Properties.Resources.txtErrorReportingStatusIdle,
	                    status.Unsubmitted,
	                    status.Submitted,
	                    status.Progress
	                    );
	            }
	            else if (status.Unsubmitted > 0)
	            {
	                this.statusImage.Image = CommonImages.StatusAtRisk24;
	
	                this.statusLabel.Text = string.Format(
	                    Properties.Resources.txtErrorReportingStatusUnsubmitted,
	                    status.Unsubmitted,
	                    status.Submitted,
	                    status.Progress
	                    );
	            }
	            else
	            {
	                this.statusImage.Image = CommonImages.StatusHealthy24;
	
	                this.statusLabel.Text = string.Format(
	                    Properties.Resources.txtErrorReportingStatusIdle,
	                    status.Unsubmitted,
	                    status.Submitted,
	                    status.Progress
	                    );
	            }
	
            }
            catch (Exception ex)
            {
                _log.Error("Failed to update error reporting status", ex);
            }
            finally
            {
                this.ResumeLayout();
            }
        }

        private void updateTimer_Tick(object sender, EventArgs e)
        {
            if (_singletonService.IsWindowsServiceRunning() == SingletonService2Factory.ServiceStatus.Running)
                UpdateErrorReportingStatus();
        }

        private void allowSubmitting_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.allowSubmitting.Checked != _tab.Settings.EnableErrorReporting)
	            {

                    // ask on activation
                    if (this.allowSubmitting.Checked &&
                        QMessageBox.Show(
                            Properties.Resources.txtErrorReportingActivateMBText,
                            Properties.Resources.txtErrorReportingActivateMBTitle,
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Question
                        ) != DialogResult.Yes)
                    {
                        this.allowSubmitting.Checked = false;

                        return;
                    }

                    _tab.Settings.EnableErrorReporting = this.allowSubmitting.Checked;

                    _tab.Services.EnableSettingsApply();
	            }
            }
            catch (Exception ex)
            {
                _log.Error("Failed to change allowance for error reporting", ex);

                QMessageBox.Show(
                    ex.Message,
                    Properties.Resources.txtErrorReportingChangeFailed,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );
            }
        }
    }
}
